#!/usr/bin/env python
# coding: utf-8
# author: Wesley

import hashlib
import json
import uuid
import logging
import random
import traceback
from .message_xsend import MESSAGEXsend
from .chuanglan import CLMessageSend
from django.core.cache import cache

from .app_configs import MESSAGE_CONFIGS, ALIDAYU_APP, CHUANGLAN_APP
from project.settings import SMS_SP
from aliyunsdkcore.client import AcsClient
from lib.sms.aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkcore.profile import region_provider
client = AcsClient(ALIDAYU_APP.appkey, ALIDAYU_APP.secret, 'cn-hangzhou')
region_provider.add_endpoint("Dysmsapi", "cn-hangzhou", "dysmsapi.aliyuncs.com")
app_logger = logging.getLogger("sms")

CACHE_FORMAT = "SMS_CODE_%s_%s"
HASH_FORMAT = "yjyx_%s_smssign"


def gencode():
    return ''.join(random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'], 4))
    # wni： 把0去掉，阿里大于有bug，首位为0的话发到用户手机会被去掉，譬如0123，到用户那为123


def sendcode(identity, target, sign=None, mcc='86'):
    if sign:
        if not checksign(target, sign):
            return {'retcode': 2, 'msg': 'invalid request'}

    if SMS_SP.SELECTED == SMS_SP.ALI_DAYU:
        return sendcode_ali_dayu(identity, target, mcc)
    elif SMS_SP.SELECTED == SMS_SP.SEND_MAIL:
        return sendcode_submail(identity, target)
    elif SMS_SP.SELECTED == SMS_SP.CL:
        return {'retcode': 1, 'msg': '未开发'}


def sendcode_submail(identity, target):
    '''
    init MESSAGEXsend class
    '''
    submail = MESSAGEXsend(MESSAGE_CONFIGS)
    #     if type(target)==str or type(target)==unicode:
    #         submail.add_to(target)
    #     elif type(target) == list:
    #         for item in target:
    #             submail.add_to(item)
    submail.add_to(target)
    submail.set_project('sG3oN')
    tmp = gencode()
    submail.add_var('code', tmp)
    cache.set(CACHE_FORMAT % (identity, target), tmp, 600)
    """
        ret should look like this:
        {"status": "success", "fee": 1, "send_id": "8441942edb089f11a7d315c1fbcc0a98", "sms_credits": "48"}
        if failed, like this:
        {
      "status":"error",
      "code":"1xx",
      "msg":"error message"
        }
        """
    ret = submail.xsend()
    if ret['status'] == 'success':
        app_logger.debug('sms send code to %s succeed. sms_credits: %s' % (target, ret['sms_credits']))
        return {'retcode': 0}
    else:
        app_logger.log(40, 'sms send code to %s failed. Code: %s. Msg: %s' % (target, ret['code'], ret['msg']))
        return {'retcode': 1001, 'msg': ret['msg']}


def sendcode_ali_dayu(identity, target, mcc='86'):

    bid = uuid.uuid1()
    real_target = str(target) if mcc.strip() == '86' else mcc.strip()+str(target)
    request = SendSmsRequest.SendSmsRequest()
    request.set_accept_format('json')
    if mcc.strip() == '86':
        request.set_TemplateCode("SMS_205435517")  # 国内模版
    else:
        request.set_TemplateCode("SMS_205134989")  # 国际模版
    code = gencode()
    request.set_TemplateParam(u'{"code": %s}' % code)
    request.set_SignName("优势星球")
    request.set_method('POST')
    request.set_PhoneNumbers(real_target)
    # 设置业务请求流水号，必填。
    request.set_OutId(bid)

    request.add_query_param('RegionId', "cn-hangzhou")

    cache.set(CACHE_FORMAT % (identity, target), code, 600)
    try:
        ret = json.loads(client.do_action_with_exception(request))
        if ret["Code"] != "OK":
            app_logger.error('sms send code to %s failed. Reason: %s' % (target, ret))
            return {'retcode': 1, 'msg': '短信发送异常!'}
        app_logger.debug('sms send code to %s succeed.' % target)
        return {'retcode': 0}
    except:
        errInfo = traceback.format_exc()
        app_logger.error(errInfo)
        app_logger.log(40, 'sms send code to %s failed' % target)
        return {'retcode': 1, 'msg': '短信发送异常!'}


def sendcode_chuanglan(identity, target, mcc='86'):
    cl = CLMessageSend({'account': CHUANGLAN_APP.account, 'host': CHUANGLAN_APP.host,
                        'password': CHUANGLAN_APP.password, 'sms_send_uri': CHUANGLAN_APP.sms_send_uri,
                        'port': CHUANGLAN_APP.port})
    real_target = str(target) if mcc.strip() == '86' else mcc.strip()+str(target)
    if mcc.strip() == '86':
        pass  # 国内模版
    else:
        pass  # 国际模版
    return {'retcode': 1, 'msg': '短信发送异常!'}


def checkcode(identity, target, codenumber):
    if codenumber == "123456":
        return {'retcode': 0}  # wni:本地调试时候用, 忽略验证码校验
    codeincache = cache.get(CACHE_FORMAT % (identity, target))
    if codeincache:
        if codeincache == codenumber:
            return {'retcode': 0}
        else:
            return {'retcode': 1, 'msg': '验证码错误'}
    else:
        return {'retcode': 1, 'msg': '验证码错误或超时，请重新获取'}


def checksign(target, sign):
    hash = hashlib.md5()
    hash.update((HASH_FORMAT % target).encode('utf-8'))
    signature = hash.hexdigest()
    if signature == sign:
        return True
    else:
        return False


def send_notice(phone, str=None):
    cl = CLMessageSend({'account': CHUANGLAN_APP.account, 'host': CHUANGLAN_APP.host,
                        'password': CHUANGLAN_APP.password, 'sms_send_uri': CHUANGLAN_APP.sms_send_uri,
                        'port': CHUANGLAN_APP.port})
    if not str:
        str = "《摩米职场课》恭喜您报名成功，请及时添加我们班主任微信哦，我们班主任会在24小时内与您联系！"
    return cl.send_sms(str, phone)


def variable_send(phone, t_result):
    cl = CLMessageSend({'account': CHUANGLAN_APP.account, 'host': CHUANGLAN_APP.host,
                        'password': CHUANGLAN_APP.password, 'sms_send_uri': CHUANGLAN_APP.variable_send_url,
                        'port': CHUANGLAN_APP.port})
    return cl.variable_send_sms(t_result.content, phone, t_result.var)